package com.appspot.android2gather.spikes;

import java.io.IOException;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.android2gather.persistance.EMF;
import com.google.gson.Gson;

public class TestServlet
    extends HttpServlet
{
    /**
     * 
     */
    private static final long serialVersionUID = -1480727721010818383L;
    private static Gson gson = new Gson();
    
    @SuppressWarnings( "unchecked" )
    @Override
    protected void doGet( HttpServletRequest req, HttpServletResponse resp )
        throws ServletException, IOException
    {

        if ( req.getParameter( "create" ) != null )
        {
            EntityManager em = EMF.get().createEntityManager();
            try
            {
                em.persist( new Coordinate(req.getParameter( "x" ), req.getParameter( "y" )) );
                resp.getWriter().println("yeah baby");
            }
            finally
            {
                em.close();
            }
           
        } else 
        {

          String queryString = "SELECT c FROM Coordinate c WHERE ";
          EntityManager em = EMF.get().createEntityManager();
          
          queryString += "( (c.x - :x1)=0 ) ";
          try
          {
              Query query = em.createQuery( queryString );
  
              // replace location params
              query.setParameter( "x1",  1 );
              //query.setParameter( "r", 5 ); 
  
              List<Coordinate> results = (List<Coordinate>) query.getResultList();
              Coordinate[] activitesInRange = new Coordinate[results.size()];
              results.toArray( activitesInRange );
              resp.getWriter().write( gson.toJson( activitesInRange, Coordinate[].class ) );
          }
          finally
          {
              em.close();
  
          }
        }
    }
}
